package com.bookpavilion.cart.controller;

import com.alibaba.fastjson.JSON;
import com.bookpavilion.cart.pojo.Cart;
import com.bookpavilion.cart.service.CartService;
import com.bookpavilion.cart.utils.CookieUtil;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import util.IdWorker;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @PostMapping("/{goodsId}/{num}")
    public Result modifyCart(@PathVariable String goodsId,@PathVariable Integer num,
    HttpServletRequest request,HttpServletResponse response){
        Claims user_claims = (Claims) request.getAttribute("user_claims");
        List<Cart> carts = (List<Cart>) find(request,response).getData();//获取当前的购物车
        carts=cartService.add(carts,goodsId,num);
        String cartStr = JSON.toJSONString(carts);
        if (user_claims==null){
            CookieUtil.setCookie(request,response,"bp_cart",cartStr);
        }else {
            String userId = user_claims.getId();
            cartService.saveCartsToRedis(userId,carts);
        }
        return new Result(true, StatusCode.OK,"添加成功");
    }

    @GetMapping()
    public Result find(HttpServletRequest request,HttpServletResponse response){
        Claims user_claims = (Claims) request.getAttribute("user_claims");
        String cookieCart = CookieUtil.getCookieValue(request, "bp_cart");
        if (cookieCart==null||cookieCart.equals("")){
            cookieCart="[]";
        }
        List<Cart> carts = JSON.parseArray(cookieCart, Cart.class);
        if (user_claims==null){
            carts= carts==null ? new ArrayList<Cart>():carts ;
            return new Result(true,StatusCode.OK,"查询成功",carts);
        }else {
            List<Cart> cartsFromRedis = cartService.findCartsFromRedis(user_claims.getId());
            if (carts!=null&&carts.size()>0){
                 cartsFromRedis= cartService.convertCartFromCookieToRedis(cartsFromRedis, carts);
                 CookieUtil.deleteCookie(request,response,"bp_cart");
                 cartService.saveCartsToRedis(user_claims.getId(),cartsFromRedis);
            }
            return new Result(true,StatusCode.OK,"查询成功",cartsFromRedis);
        }
    }
}
